package com.soft.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.soft.dto.CommentResponse;
import com.soft.entity.Comment;
import com.soft.entity.User;
import com.soft.mapper.CommentMapper;
import com.soft.service.CommentService;
import com.soft.service.SensitiveWordService;
import com.soft.service.UserService;

/**
 * 评论服务实现：包含递归删除子评论、敏感词标记，以及将评论组装为树形结构。
 */
@Service
public class CommentServiceImpl implements CommentService {
    @Autowired
    private CommentMapper commentMapper;
    
    @Autowired
    private UserService userService;

    @Override
    public boolean addComment(Comment comment) {
        return commentMapper.insert(comment) > 0;
    }

    @Override
    public boolean deleteComment(Integer commentId) {
        try {
            // 1) 先递归删除所有子评论，避免留下孤儿引用
            deleteRepliesRecursively(commentId);
            
            // 2) 再删除该评论本身
            return commentMapper.deleteById(commentId) > 0;
        } catch (Exception e) {
            System.err.println("删除评论时发生异常: " + e.getMessage());
            e.printStackTrace();
            return false;
        }
    }
    
    /**
     * 递归删除所有回复评论
     */
    /** 递归删除某条评论的所有子回复 */
    private void deleteRepliesRecursively(Integer parentCommentId) {
    // 1) 查找所有回复该评论的子评论
        List<Comment> replies = commentMapper.selectList(
            new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<Comment>()
                .eq("reply_to", parentCommentId)
        );
        
    // 2) 递归删除每个子评论
        for (Comment reply : replies) {
            deleteRepliesRecursively(reply.getCommentId());
            commentMapper.deleteById(reply.getCommentId());
        }
    }

    @Override
    public boolean updateComment(Comment comment) {
        return commentMapper.updateById(comment) > 0;
    }

    @Override
    public Comment getCommentById(Integer commentId) {
        return commentMapper.selectById(commentId);
    }

    @Override
    public List<Comment> listCommentsByWorklogId(Integer worklogId) {
    // 1) 读取与工作日志关联的评论
    return commentMapper.selectList(
            new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<Comment>()
                .eq("related_type", "worklog")
                .eq("related_id", worklogId)
        );
    }

    @Override
    public List<Comment> listCommentsByScheduleId(Integer scheduleId) {
    // 1) 读取与日程关联的评论
    return commentMapper.selectList(
            new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<Comment>()
                .eq("related_type", "schedule")
                .eq("related_id", scheduleId)
        );
    }

    @Override
    public List<Comment> listAll() {
        return commentMapper.selectList(null);
    }
    
    @Autowired
    private SensitiveWordService sensitiveWordService;
    
    @Override
    public List<Comment> listAllForAdmin() {
        // 管理员专用：返回原始评论内容并标记敏感词
        List<Comment> comments = commentMapper.selectList(null);
        
        // 为管理员显示原始内容并标记敏感词
        for (Comment comment : comments) {
            try {
                String content = comment.getContent();
                
                if (comment.getOriginalContent() != null && !comment.getOriginalContent().isEmpty()) {
                    // 如果有原始内容，使用原始内容
                    content = comment.getOriginalContent();
                } else {
                    // 如果没有原始内容，检查当前内容是否包含敏感词
                    if (content != null) {
                        List<String> sensitiveWords = sensitiveWordService.findSensitiveWords(content);
                        if (!sensitiveWords.isEmpty()) {
                            // 如果检测到敏感词，添加标记
                            content = content + " [包含敏感词: " + String.join(", ", sensitiveWords) + "]";
                        } else if (content.contains("***")) {
                            // 如果内容包含***但检测不到敏感词，说明是旧数据被过滤过
                            content = content + " [已被敏感词过滤]";
                        }
                    }
                }
                
                comment.setContent(content);
            } catch (Exception e) {
                // 如果处理失败，保持原内容不变
                System.err.println("处理管理员评论内容失败: " + e.getMessage());
            }
        }
        
        return comments;
    }
    
    @Override
    public List<CommentResponse> listCommentsWithRepliesByWorklogId(Integer worklogId) {
    // 1) 取出平铺的评论列表（按时间升序）
    List<Comment> comments = commentMapper.selectList(
            new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<Comment>()
                .eq("related_type", "worklog")
                .eq("related_id", worklogId)
                .orderByAsc("create_time")
        );
    // 2) 组装为树形结构并补齐昵称
    return buildCommentTree(comments);
    }
    
    @Override
    public List<CommentResponse> listCommentsWithRepliesByScheduleId(Integer scheduleId) {
    // 1) 取出与日程相关的评论（按时间升序）
    List<Comment> comments = commentMapper.selectList(
            new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<Comment>()
                .eq("related_type", "schedule")
                .eq("related_id", scheduleId)
                .orderByAsc("create_time")
        );
    // 2) 转换树形
    return buildCommentTree(comments);
    }
    
    /** 将平铺列表按 replyTo 组织为树结构，并补齐昵称 */
    private List<CommentResponse> buildCommentTree(List<Comment> comments) {
    // 1) 为了拼接昵称，先收集所有涉及到的用户ID
        List<Integer> userIds = comments.stream()
            .map(Comment::getCreatorId)
            .distinct()
            .collect(Collectors.toList());
        
    // 2) 构建 userId->nickname 的映射，缺省回退 username 或“未知用户”
    Map<Integer, String> userNicknameMap = userIds.stream()
            .collect(Collectors.toMap(
                userId -> userId,
                userId -> {
                    User user = userService.getById(userId);
                    return user != null ? (user.getNickname() != null ? user.getNickname() : user.getUsername()) : "未知用户";
                }
            ));
        
    // 3) 把实体转换为响应对象，预置空的 replies
        List<CommentResponse> responseList = comments.stream()
            .map(comment -> {
                CommentResponse response = new CommentResponse();
                response.setCommentId(comment.getCommentId());
                response.setRelatedType(comment.getRelatedType());
                response.setRelatedId(comment.getRelatedId());
                response.setCreatorId(comment.getCreatorId());
                response.setNickname(userNicknameMap.get(comment.getCreatorId()));
                response.setContent(comment.getContent());
                response.setReplyTo(comment.getReplyTo());
                response.setCreateTime(comment.getCreateTime());
                response.setReplies(new ArrayList<>());
                return response;
            })
            .collect(Collectors.toList());
        
    // 4) 构造树形结构：replyTo 为空的是根节点，否则挂到父节点
        Map<Integer, CommentResponse> commentMap = responseList.stream()
            .collect(Collectors.toMap(CommentResponse::getCommentId, comment -> comment));
        
        List<CommentResponse> rootComments = new ArrayList<>();
        
        for (CommentResponse comment : responseList) {
            if (comment.getReplyTo() == null) {
                // 顶级评论
                rootComments.add(comment);
            } else {
                // 回复评论
                CommentResponse parent = commentMap.get(comment.getReplyTo());
                if (parent != null) {
                    parent.getReplies().add(comment);
                }
            }
        }
        
        return rootComments;
    }
}
